<template>
	<gui-page :customHeader="true" :headerClass="['gui-bg-white']" ref="guiPage" :fullPage="true">
		<!-- 自定义头部导航 -->
		<template v-slot:gHeader>
			<view style="height:44px;" class="gui-flex gui-nowrap gui-rows gui-align-items-center">
				<!-- 使用组件实现返回按钮及返回首页按钮 -->
				<gui-header-leading :home="false"></gui-header-leading>
				<!-- 导航文本此处也可以是其他自定义内容 -->
				<view style="width:44rpx;"></view>
				<text class="gui-flex1 gui-text-center gui-ellipsis">改异常</text>
				<!-- 此处加一个右侧展位元素与左侧同宽，实现标题居中 -->
				<!-- 实际宽度请根据自己情况设置 -->
				<view style="width:120rpx;"></view>
				<!-- 如果右侧有其他内容可以利用条件编译和定位来实现-->
			</view>
		</template>

		<template v-slot:gBody>
			<view class="gui-relative">
				<view class="hulu-main">

					<view class="gui-padding">
						<text class="gui-text gui-color-black">维修信息</text>
					</view>
					<view class="hulu-bg-color5">
						<u-grid :border="true" :align="'center'" v-if="ticket.repair">
							<u-grid-item bgColor="#68a6ec">
								<view class="info" style="font-weight: bolder;">
									<view class="hulu-text-color3 hulu-font-4 gui-text-center hulu-primary-color1">单号
									</view>
									<view class="hulu-text-color7" style="font-size: 24rpx;word-break: break-all;">
										{{ticket.repair.order_no}}
									</view>
								</view>
							</u-grid-item>
							<u-grid-item bgColor="#68a6ec">
								<view class="info" style="font-weight: bolder;">
									<view class="hulu-text-color3 hulu-font-4 gui-text-center hulu-primary-color1">车牌
									</view>
									<view class="" style="word-break: break-all;">
										{{ticket.repair.license}}
									</view>
								</view>
							</u-grid-item>
							<u-grid-item bgColor="#68a6ec">
								<view class="info" style="font-weight: bolder;">
									<view class="hulu-text-color3 hulu-font-4 gui-text-center hulu-primary-color1">电话
									</view>
									<view class="hulu-text-color7 " style="word-break: break-all;">
										{{ticket.repair.phone}}
									</view>
								</view>
							</u-grid-item>
							<u-grid-item bgColor="#68a6ec">
								<view class="info" style="font-weight: bolder;">
									<view class="hulu-text-color3 hulu-font-4 gui-text-center hulu-primary-color1">联系人
									</view>
									<view class="hulu-text-color7 " style="word-break: break-all;">
										{{ticket.repair.user_name}}
									</view>
								</view>
							</u-grid-item>
							<u-grid-item bgColor="#68a6ec">
								<view class="info" style="font-weight: bolder;">
									<view class="hulu-text-color3 hulu-font-4 gui-text-center hulu-primary-color1">描述
									</view>
									<view class="hulu-text-color7 " style="word-break: break-all;">
										{{ticket.repair.description}}
									</view>
								</view>
							</u-grid-item>
							<u-grid-item bgColor="#68a6ec">
								<view class="info" style="font-weight: bolder;">
									<view class="hulu-text-color3 hulu-font-4 gui-text-center hulu-primary-color1">位置
									</view>
									<view class="hulu-text-color7 " style="font-size: 24rpx;word-break: break-all;">
										{{ticket.repair.address}}
									</view>
								</view>
							</u-grid-item>
						</u-grid>
					</view>
					<view class="gui-padding">
						<text class="gui-text gui-color-black">派单信息</text>
					</view>
					<view class="hulu-bg-color5">
						<u-grid :border="true" :align="'center'">
							<u-grid-item bgColor="#f0c8bb">
								<view class="info" style="font-weight: bolder;">
									<view class="hulu-font-4 gui-text-center">车位
									</view>
									<view class="hulu-text-color7 hulu-btn-text-color"
										style="font-size: 24rpx;word-break: break-all;">
										{{ticket.parking?`${ticket.parking.parking_type}${ticket.parking.no}`:''}}
									</view>
								</view>
							</u-grid-item>
							<u-grid-item bgColor="#f0c8bb">
								<view class="info" style="font-weight: bolder;">
									<view class="hulu-font-4 gui-text-center">车型
									</view>
									<view class="hulu-text-color7 hulu-btn-text-color"
										style="font-size: 24rpx;word-break: break-all;">
										{{ticket.kind?`${ticket.kind.union_name}`:''}}
									</view>
								</view>
							</u-grid-item>
							<u-grid-item bgColor="#f0c8bb">
								<view class="info" style="font-weight: bolder;">
									<view class="hulu-font-4 gui-text-center">维修工
									</view>
									<view class="hulu-text-color7 hulu-btn-text-color"
										style="font-size: 24rpx;word-break: break-all;">
										{{ticket.users?`${ticket.users.map(i=>i.name).toString()}`:''}}
									</view>
								</view>
							</u-grid-item>
							<u-grid-item bgColor="#f0c8bb">
								<view class="info" style="font-weight: bolder;">
									<view class="hulu-font-4 gui-text-center">维修项目
									</view>
									<view class="hulu-text-color7 hulu-btn-text-color"
										style="font-size: 24rpx;word-break: break-all;">
										{{ticket.services?`${ticket.services.map(i=>i.name).toString()}`:''}}
									</view>
								</view>
							</u-grid-item>
							<u-grid-item bgColor="#f0c8bb">
								<view class="info" style="font-weight: bolder;">
									<view class="hulu-font-4 gui-text-center">方式
									</view>
									<view class="hulu-text-color7 hulu-btn-text-color"
										style="font-size: 24rpx;word-break: break-all;">
										{{ticket.repair_way==1?`门店`:'应急'}}
									</view>
								</view>
							</u-grid-item>
							<u-grid-item bgColor="#f0c8bb">
								<view class="info" style="font-weight: bolder;">
									<view class="hulu-font-4 gui-text-center">派单时间
									</view>
									<view class="hulu-text-color7 hulu-btn-text-color"
										style="font-size: 24rpx;word-break: break-all;">
										{{ticket.created_at}}
									</view>
								</view>
							</u-grid-item>

						</u-grid>
					</view>
					<view class="gui-padding gui-flex gui-space-between">
						<view class="gui-text gui-color-black">
							工时<text
								class="hulu-text-state1 hulu-font-4 ">【{{manhours.reduce((pres,curr)=>pres+curr.score,0)}}】</text>
						</view>
						<view class="gui-text gui-color-black">
							改后工时<text
								class="hulu-text-state1 hulu-font-4 ">【{{manhours.reduce((pres,curr)=>pres+curr.score,0)+(+addScore)}}】</text>
						</view>
					</view>

					<view class="form gui-padding gui-bg-white">
						<up-form labelPosition="left" :model="state.model" :rules="state.rules" ref="formRef1"
							style="z-index:1;">

							<up-form-item label="服务" prop="ticketState.service_ids" borderBottom>
								<view class="">
									<next-search-select :multiple="true" :list="state.serviceopts" label-key="name"
										value-key="id" placeholder="选择服务" title="服务列表" @visibleChange="visibleChange"
										v-model:value="state.model.ticketState.service_ids" @search="searchFunc"
										clearable></next-search-select>

								</view>
							</up-form-item>
							<up-form-item label="人员" prop="ticketState.user_ids" borderBottom>
								<next-search-select :multiple="true" :list="state.useropts" label-key="name"
									value-key="id" placeholder="选择维修工" title="维修工列表" @visibleChange="visibleChange1"
									@change="changeUser" v-model:value="state.model.ticketState.user_ids"
									@search="searchFunc1" clearable></next-search-select>
							</up-form-item>
							<up-form-item label="手工" borderBottom>
								<up-radio-group v-model="state.model.ticketState.hand" @change="groupChange">
									<up-radio :customStyle="{marginLeft: '8px'}" label="系统" name="1" value="1">
									</up-radio>
									<up-radio :customStyle="{marginLeft: '8px'}" label="手工" name="2" value="2">
									</up-radio>
								</up-radio-group>
							</up-form-item>

							<up-form-item label="工时增设" borderBottom v-if="state.model.ticketState.hand=='2'">
								<view class="gui-flex gui-space-between">
									<input type="number" placeholder="请输入额外工时" v-model="addScore" />
									<text class="hulu-text-color5 hulu-font-5">待分配
									{{noAssigned}}
									</text>
								</view>
							</up-form-item>

							<up-form-item label="分配" borderBottom v-if="state.model.ticketState.hand=='2'">
								<view class="">
									<view class="" style="">
										<!-- 当只有一个员工时直接添加 -->
										<view class="" v-for="(user,index) in ticket.users" :key="index">
											<view
												class="gui-flex gui-space-between gui-align-items-center gui-margin-top gui-border-b hulu-primary-color1">
												<text style="width:120rpx;">{{user.name}}</text>
												<up-number-box step="0.5"  button-size="24" :name="user.id" :min="0"
													
													@change="valChange1"></up-number-box>
												<button type="default" :disabled="originUserIds.some(i=>i==user.id)" 
													class="gui-button gui-button-mini gui-bg-red gui-noborder" @click="subUser(index)"
													style="width:66rpx;border-radius: 50%;">
													<text
														class="gui-block gui-color-white gui-button-text-mini gui-icons" style="font-weight: bolder;">&#xe62d;</text>
												</button>
											</view>
										</view>
										<!-- 当有多个员工时出现分别为每一个员工设置工时 -->
									</view>
								</view>
							</up-form-item>

							<view class="gui-margin-top">
								<button type="default" style="border-radius:80rpx;" @tap="onSubmit"
									class="gui-button  gui-bg-orange1 gui-noborder">
									<text class="gui-color-white gui-button-text">确认改派</text>
								</button>
							</view>
						</up-form>
					</view>

				</view>
				<view class="" style="height:68rpx;">

				</view>
			</view>
		</template>
	</gui-page>
</template>
<script>
	import useOpt from "@/api/option";
	import useTicket from "@/api/ticket";
	import useManhour from "@/api/manhour";
	import graceJS from '@/Grace6/js/grace.js';

	const {
		getOpt,
		loadExceptUserOpt,
		loadExceptServiceOpt
	} = useOpt()
	const {
		LoadManhour
	} = useManhour()
	const {
		ticketStart,
		showTicket,
		changeAbnormal
	} = useTicket()
	export default {
		data() {
			return {
				addScore: 0,
				manhours: [],
				ticket: {},
				originUserIds:[],//原始维修工
				state: {
					showParking: false,
					showKind: false,
					showType: false, //正常或者异常维修
					wayopts: [],
					parkingopts: [],
					kindopts: [],
					serviceopts: [],
					useropts: [],
					model: {
						ticketState: {
							id: null,
							ticket_type: 2, //异常工单
							service_ids: [],
							user_ids: [],
							hand: "1",
							score_assigns: []
						},
					},
					rules: {
						'ticketState.service_ids': {
							type: 'array',
							required: true,
							message: '请选服务',
							trigger: ['blur', 'change'],
						},
						'ticketState.user_ids': {
							type: 'array',
							required: true,
							message: '请选维修工',
							trigger: ['blur', 'change'],
						},
						'ticketState.parking_id': {
							type: 'number',
							required: true,
							message: '请填库位',
							trigger: ['blur', 'change'],
						},
						'ticketState.kind_id': {
							type: 'number',
							required: true,
							message: '请填类型',
							trigger: ['blur', 'change'],
						},
						'ticketState.repair_way': [{
							type: 'number',
							required: true,
							message: '请输入类型',
							trigger: ['blur', 'change'],
						}, ],

					},
				},

			}
		},
		created() {

		},
		computed:{
			noAssigned(){
				return this.manhours.reduce((pres,curr)=>pres+curr.score,0)+(+this.addScore)-this.state.model.ticketState.score_assigns.reduce((p,c)=>p+c.score,0)
			}
		},
		async mounted() {
			const {
				data
			} = await getOpt()
			this.state.parkingopts = data.parkings
			this.state.kindopts = data.kinds
		},
		onLoad(option) {
			this.state.model.ticketState.id = +(option.id)
			this.getTicket()
		},
		methods: {
			//删除选项
			subUser(index){
				//1-删除这个选项
				this.ticket.users.splice(index,1)
				// 2-从新计算工时
				this.state.model.ticketState.score_assigns.splice(index,1)
			},
			changeUser(val) {
				console.log("-----", val)
				let exist = this.ticket.users.some(item => item.id == val.id)
				let opt = this.t
				if (!exist) {
					this.ticket.users.push({
						id: val.id,
						name: val.name
					})
					this.state.model.ticketState.score_assigns.push({
						user_id: val.id,
						score: 1
					})
				}
			},
			valChange1(val) {
				console.log(val)
				let index = this.state.model.ticketState.score_assigns.findIndex(s => s.user_id == val.name)
				if (index != -1) {
					this.state.model.ticketState.score_assigns[index]['score'] = val.value
				}
				console.log(this.state.model.ticketState.score_assigns)
			},

			groupChange(e) {
				console.log(e)
			},
			visibleChange() {},
			visibleChange1() {},
			async searchFunc1(val) {
				console.log("搜索的维修工关键字：", val)
				uni.showLoading({
					title: '请稍后...',
					icon: 'none'
				})
				// 模拟ajax请求
				console.log(this.ticket.services)
				let user_ids = this.ticket.users.map(item => item.id)
				const res = await loadExceptUserOpt(val, user_ids)
				this.state.useropts = res.data
				uni.hideLoading()
			},
			async searchFunc(val) {
				//服务
				console.log("搜索的服务关键字：", val)
				uni.showLoading({
					title: '请稍后...',
					icon: 'none'
				})
				// 模拟ajax请求
				let service_ids = this.ticket.services.map(item => item.id)
				const res = await loadExceptServiceOpt(val, service_ids)
				this.state.serviceopts = res.data
				uni.hideLoading()
			},

			radioChange(e) {
				this.state.model.ticketState.parking_id = (+e.target.value)
				this.$refs.guipopup2.close()
			},
			radioChange2(e) {
				this.state.model.ticketState.kind_id = (+e.target.value)
				this.$refs.guipopup3.close()
			},
			showParking() {
				this.$refs.guipopup2.open()
			},
			showKind() {
				this.$refs.guipopup3.open()
			},

			async getTicket() {
				const {
					data
				} = await showTicket(this.state.model.ticketState.id)
				this.ticket = data
				const res = await LoadManhour({
					service_ids: this.ticket.services.map(item => item.id),
					kind_id: this.ticket.kind_id
				})
				// console.log(res)
				this.manhours = res.data
				//初始化待分配工时
				this.state.model.ticketState.score_assigns = this.ticket.users.map(item => {
					return {
						user_id: item.id,
						score: 1,
					}
				})
				this.originUserIds=this.ticket.users.map(item=>item.id)

				console.log(this.state.model.ticketState)
			},
			onTapImage(i) {
				uni.previewImage({
					current: i + 1,
					urls: this.ticket.repair.images
				})
			},
			onSubmit() {
				//当方式为手工时，走分配逻辑校验。
				if(this.state.model.ticketState.hand=="2"){
					if(this.noAssigned!=0){
						uni.showToast({
							icon:"none",
							title:"分配工时错误"
						})
						return ;
					}
				}
				console.log(this.state.model.ticketState)
				this.$refs.formRef1.validate().then(async valid => {
					if (valid) {
						uni.$u.toast('校验通过')
						await changeAbnormal(this.state.model.ticketState)
						this.$refs.formRef1.resetFields()
						uni.reLaunch({
							url:`/pages/ticket/index`
						})
					} else {
						uni.$u.toast('校验失败')
					}
				}).catch((e) => {
					// 处理验证错误  
					console.error(e)
					uni.$u.toast('校验失败')
				});

			},

		},
	}
</script>
<style lang="scss">
	.custom-style {
		color: #ff0000;
		width: 400rpx;
	}

	.hulu-main {
		padding: 0 24rpx;
		box-sizing: border-box;

		.info {
			height: 120rpx;
			box-sizing: border-box;
		}
	}
</style>